﻿using Core.Com;
using Reader.RFID.Models;
using System;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace Reader.RFID.Forms
{
    public partial class FrmConfig : Form
    {

        public FrmConfig()
        {
            InitializeComponent();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            var config = prop.SelectedObject as Config;
            if (config != null)
            {
                var json = config.ToJson(Newtonsoft.Json.NullValueHandling.Include);
                var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"Iots", "Reader.RFID.json");

                using (System.IO.StreamWriter sw = new System.IO.StreamWriter(path, false, Encoding.UTF8))
                {
                    sw.Write(json);
                }
            }
            //更新json文件
            this.DialogResult = DialogResult.OK;
        }

        private void FrmConfig_Load(object sender, EventArgs e)
        {
            try
            {
                var json = "";
                var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Iots", "Reader.RFID.json");
                if (!File.Exists(path))
                {
                    using (System.IO.StreamWriter sw = new System.IO.StreamWriter(path, false, Encoding.UTF8))
                    {
                        sw.Write(new Config().ToJson(Newtonsoft.Json.NullValueHandling.Include));
                    }
                }
                //读取json文件
                using (System.IO.StreamReader sr = new System.IO.StreamReader(path))
                {
                    json = sr.ReadToEnd();
                }
                var config = json.FromJson<Config>();
                if (config == null)
                {
                    this.prop.Visible = false;
                    this.lblError.Visible = true;
                    return;
                }
                prop.SelectedObject = config;
            }
            catch (Exception ex)
            {
                this.prop.Visible = false;
                this.lblError.Visible = true;
                lblError.Text = ex.Message;
            }

        }

        private void FrmConfig_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (DialogResult != DialogResult.OK)
                this.DialogResult = DialogResult.Cancel;
        }
    }
}
